<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="(item, index) in breadList"
          :key="index"
          :to="{ path: item.path }"
        >
          {{ item.meta.title }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          status-icon
          size="large"
        >
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="ruleForm.title" @input="checkTitle" />
          </el-form-item>
          <el-form-item label="文章描述" prop="desc">
            <el-input
              v-model="ruleForm.desc"
              style="width: 1040px"
              :rows="3"
              type="textarea"
              show-desc
            />
          </el-form-item>

          <el-form-item label="文章状态" prop="categeory">
            <el-radio-group v-model="ruleForm.categeory">
              <el-radio :label="0">停用</el-radio>
              <el-radio :label="1">正常</el-radio>
            </el-radio-group>
          </el-form-item>
<!-- 
          <el-form-item label="景点">
            <el-select v-model="region" placeholder="请选择景点">
            <el-option  label="故宫" value="故宫" />
            <el-option  label="长城" value="长城" />
            <el-option  label="威海公园" value="威海公园" />
            <el-option  label="烟台山" value="烟台山" />
            </el-select>
          </el-form-item> -->

          <el-form-item label="文章内容" prop="content">
            <!-- <el-input v-model="ruleForm.a_content"  /> -->
            <!-- <mavon-editor v-model="ruleForm.a_content" style="width: 100%;" ref="md" @imgAdd="imgAdd"
              @imgDel="imgDel" /> -->
              <div style="border: 1px solid #ccc">
                <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                  :mode="mode" />
                <Editor style="height: 500px; overflow-y: hidden;" v-model="ruleForm.content" :defaultConfig="editorConfig"
                  :mode="mode" @onCreated="handleCreated" />

              </div>

              
          </el-form-item>

        </el-form>
      </div>
      <div>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >发表</el-button
        >
        <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { useRouter, useRoute } from "vue-router";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { onBeforeUnmount, ref, shallowRef, onMounted, reactive, watch ,computed} from 'vue';
import request from "../../utils/request";
import { ElMessage, ElNotification } from "element-plus";
import { useUserStore } from '../../stores/userStore';  

const userStore = useUserStore(); // 引入用户 store  

// wangeditor编辑器--------
// wangeditor编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML

const toolbarConfig = {}
const editorConfig = { MENU_CONF: {} }
editorConfig.MENU_CONF['uploadImage'] = {
  //服务端地址
  server: 'http://localhost:3000/article/upload-img',
  // form-data fieldName ，默认值 'wangeditor-uploaded-image'
  fieldName: 'imgfile',
  // 单个文件的最大体积限制，默认为 2M
  maxFileSize: 1 * 1024 * 1024, // 1M
  // 最多可上传几个文件，默认为 100
  maxNumberOfFiles: 5,
  // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
  allowedFileTypes: ['image/*'],
  // 超时时间，默认为 10 秒
  timeout: 5 * 1000, // 5 秒
  onSuccess(file, res) {          // JS 语法
    console.log(`${file.name} 上传成功`, res)
  },
  onFailed(file, res) {           // JS 语法
    console.log(`${file.name} 上传失败`, res)
  },
}
editorConfig.MENU_CONF['insertImage'] = {
    onInsertedImage(imageNode) {                    // JS 语法
        if (imageNode == null) return
        const { src, alt, url, href } = imageNode
        const imageList1 = []
        //上传的图片信息，需要与最后提交的进行比较，删除服务器的多余图片
        imageList1.push(imageNode)
    }
}
const mode = 'default'
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
// wangeditor编辑器-----------


const userInfo = localStorage.getItem("userInfo")
// 获取登录用户的 ID  
const userId = computed(() => userStore.userId);
const userName = computed(() => userStore.username);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);
const fileList = ref([]);
const upload = ref(null);


const user = JSON.parse(localStorage.getItem("userInfo")).user
// 移除图片
const handledel = (file) => {
  fileList.value = fileList.value.filter((i) => {
    return i.uid !== file.uid;
  });
};



let breadList = []; // 路由集合
const route = useRoute();
const router = useRouter();
const getBreadcrumb = (url) => {
  let matched = url.matched;
  //如果不是首页
  if ("Home" == matched[0].name) {
    matched[0].meta = { title: "系统首页" };
  }
  breadList = matched;
};
watch(
  route,
  (newValue, oldValue) => {
    // console.log(222222,newValue)
    getBreadcrumb(newValue);
  },
  { deep: true, immediate: true }
);

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};


//添加文章
const submitForm = async (formEl) => {
    //最后真正提交的图片的数据信息
  const imageList2  = editorRef.value.getElemsByType('image')
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    const formData = new FormData();
    fileList.value.forEach((value, index) => {
      formData.append("imgfile", value.raw);
    });
    //title, desc, categeory, author, content
    formData.append("title", ruleForm.title);
    formData.append("desc", ruleForm.desc);
    formData.append("categeory",ruleForm.categeory);
    formData.append("author", userName.value); 
    formData.append("content", ruleForm.content);
    formData.append("userId", user.userId); // 添加当前用户ID
    console.log( ruleForm.title,userId.value,userName.value)
    if (valid) {
      console.log("提交更新", fields);
      //发送ajax请求
      request
      .post("/article/addArticle",formData,{
          headers:{
            "Content-Type":
            "multipart/form-data;charset=UTF-8; boundary=<calculated when request is sent>",
          },
        })
        .then((res) => {
          // 处理响应
          if (res.data.code === 200) {
            ElNotification({
              title: "发表文章成功",
              message: "文章添加成功",
              type: "success",
            });
            // 重置页面数据
            // formEl.resetFields();
            router.push("/articleInfo");
          }
        });
    } else {
      ElNotification({
        title: "校验失败",
        message: "请重新填写信息",
        type: "error",
      });
    }
  });
};
const ruleForm = reactive({
  //       //title, desc, categeory, author, content
  title: "",
  desc: "",
  categeory: "",
  content: "<p>请输入文章内容.......</p>",
});
const rules = reactive({
  title: [
    {
      required: true,
      message: "请输入文章标题",
      // trigger: ["blur", "change"], // 不加这行效果一致
    },
    {
      pattern: /^\S*$/, // 正则表达式校验用户名，不允许空格
      message: "用户名中不能有空格",
    },
    // {
    //   pattern: /^[a-zA-Z0-9_]+$/, // 正则表达式校验用户名，只允许字母、数字和下划线
    //   message: "用户名只能包含字母、数字和下划线",
    //   trigger: ["blur", "change"],
    // },
  ],
  desc: [
    {
      required: true,
      message: "请输入文章描述",
    },
  ],
                        //title, desc, categeory, author, content

  // address: [
  //   {
  //     required: false,
  //     message: "请输入地址",
  //     trigger: "blur",
  //   },
  // ],
  categeory: [
    {
      required: true,
      message: "请选择文章类型",
      trigger: "change",
    },
  ],
  content: [
    {
      required: true,
      message: "请输入文章内容",
    },
  ],
  // u_img: [
  //   {
  //     required: true,
  //     message: "请上传用户头像",
  //     trigger: "change",
  //   },
  // ],
});
const ruleFormRef = ref();
const centerDialogVisible = ref(false);
</script>

<style>
.hidden .el-upload--picture-card {
  display: none;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
